/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Chat;

import java.awt.Button;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author snake_gt
 */
public class ServidorInterfaz implements ActionListener{
    private TextArea area;
    private Button boton;
    private Label etiqueta;
    private Frame ventana;
    private ServerSocket server;
    private Socket socket;
    private Map lista;

    public void actionPerformed(ActionEvent e){
        try {
            server = new ServerSocket(8989);
            etiqueta.setText("Servidor Iniciado");
            area.setText("En espera de conexiones\n");
            while(true){
                socket=server.accept();
                DataInputStream in=new DataInputStream(socket.getInputStream());
                String nombre=in.readUTF();
                lista.put(nombre, socket);
                String contactos="";
                for (Object o:lista.keySet())
                    
                    contactos=contactos+",";
                for (Object o:lista.values()){
                Socket ss=(Socket)o;
                DataOutputStream out=new DataOutputStream(ss.getOutputStream());
                out.writeUTF(contactos);

                    area.setText(area.getText()+"LLego un cliente....."+nombre+"\n");
                Thread t = new Thread(new HiloServer(socket, area, lista));
                t.start();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public ServidorInterfaz() {
        area= new TextArea();
        boton = new Button("Iniciar");
        etiqueta = new Label("Servidor Detenido");
        ventana= new Frame();
        ventana.add(etiqueta,"North");
        ventana.add(area);
        ventana.add(boton,"South");
        boton.addActionListener(this);
        ventana.setSize(400,400);
        ventana.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        lista = new HashMap<String,Socket>();
    }
    
    public void iniciar(){
        ventana.setVisible(true);
    }

    public static void main(String[] args) {
        ServidorInterfaz si = new ServidorInterfaz();
        si.iniciar();

    }


}
